
import org.json.simple.JSONObject;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * 长连接方式
 * 服务端
 */
public class Server {
    public static void main(String[] args) {
        System.out.println("Socket服务器开始运行...");
        try {
            //服务端初始化
            ServerSocket serverSocket = new ServerSocket(9999);
            //创建一个serverSocket在端口9999监听客户请求
            while (true){
                //获取客户端
                Socket socket = serverSocket.accept();//接受客户端请求

                //服务端监听线程
                Thread threadServerListen = new Thread(new ServerListen(socket));
                threadServerListen.start();

                //服务端发送线程
                Thread threadServerSend = new Thread(new ServerSend(socket));
                threadServerSend.start();
            }
        }catch (Exception e){

        }

    }
}

/**
 * 服务端监听线程
 */
class ServerListen implements Runnable{

    private Socket socket;

    public ServerListen(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try{
            //获取对象输入流
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            //getInputStream方法得到的是一个输入流，服务端的Socket对象上的getInputStream方法得到的输入流其实就是从客户端发送给服务器端的数据流
            while(true){//while循环保持监听状态
                System.out.println(ois.readObject());
            }
        }catch (Exception e){
            try {
                socket.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

/**
 * 服务端发送线程
 */
class ServerSend implements Runnable{

    private Socket socket;

    public ServerSend(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //获取对象输出流
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            //getOutputStream方法得到的是一个输出流，服务端的Socket对象上的getOutputStream方法得到的输出流其实就是发送给客户端的数据
            Scanner scanner = new Scanner(System.in);
            while(true){
                System.out.println("请输入要发送的内容...");
                String string = scanner.nextLine();
                //https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple
                JSONObject object = new JSONObject();
                object.put("To client",socket.getInetAddress()+":"+socket.getPort());
                object.put("type","chat");
                object.put("msg",string );
                oos.writeObject(object);
                oos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}